/*
版权@hehung所有，转载请申明
email：1398660197@qq.com
*/
#include "app_kv.h"
#include <board.h>
#include <aos/kv.h>
#include <string.h>


static const char *kv_name[] = 
{
    "VolumeV",
    "SoundE",
    "SoundT",
    "Ntp",
    "City",
    "Ssid",
    "Pwd",
    "Ssid_len",
    "Pwd_len",
    "Clock1",
    "Clock2",
    "Clock3",
    "Clock4",
    "Clock5",
    "Clock6",
    "Clock7",
    "Clock8",
    "Clock9",
    "Clock10"
};

/*
kv_sta_name:
bit0 - VolumeV
...
bit18 - Clock10
*/
static const char kv_sta_name[8] = "InitSta";

/* 用于标记某一个设置项是否存储了 */
static int kv_saved_flag = KV_NONE;


/* 获取存储至初始化状态 */
void Kv_Init(void)
{
    aos_kv_getint(kv_sta_name, &kv_saved_flag);
}

/* 获取某一个存储值是否被存储在KV中了 
1 - 已经存储在了KV中
0 - 还没有存储在KV中*/
uint8_t Kv_GetSaveStatus(e_KvSaveType kv_num)
{
    return ((kv_saved_flag >> kv_num) & 0x01U);
}

/* 设置KV键值 */
void Kv_WriteData(e_KvSaveType kv_num, int value)
{
    int ret; 
    int read_v;

    read_v = Kv_ReadData(kv_num);
    /* 当值不同时才会更新 */
    if (read_v != value)
    {
        ret = aos_kv_setint(kv_name[kv_num], value);
    }
	
    (void)ret;
    /* 用于标记该值已经存储了 */
    kv_saved_flag |= (1 << kv_num);
    aos_kv_setint(kv_sta_name, kv_saved_flag);
}

/* 获取KV键值 */
int Kv_ReadData(e_KvSaveType kv_num)
{
	int value;
    int ret; 
	
	ret = aos_kv_getint(kv_name[kv_num], &value);

	(void)ret;
	return value;
}

/* 存储字符串KV */
void Kv_WriteDataString(e_KvSaveType kv_num, char *wDate, int len)
{
    int ret; 
    char read_d[64];

    (void)Kv_ReadDataString(kv_num, read_d, len+1);

    /* 当值不同时才会更新 */
    if (strcmp(read_d, wDate) != 0)
    {
        ret = aos_kv_setstring(kv_name[kv_num], wDate);
    }
	
    (void)ret;
    /* 用于标记该值已经存储了 */
    kv_saved_flag |= (1 << kv_num);
    aos_kv_setint(kv_sta_name, kv_saved_flag);
}

/* 获取KV键值字符串 */
int Kv_ReadDataString(e_KvSaveType kv_num, char *rData, int len)
{
    int ret; 
	
	ret = aos_kv_getstring(kv_name[kv_num], rData, len+1);

	return ret;
}

/* 删除KV键值 */
void Kv_DelData(e_KvSaveType kv_num)
{
	(void)aos_kv_del(kv_name[kv_num]);

    /* 用于表示该值未存储 */
    kv_saved_flag &= (~ (1 << kv_num));
}


